/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.msg;

import cn.ac.iie.di.datadock.rdata.exchange.client.exception.RESessionException;
import cn.ac.iie.di.datadock.rdata.exchange.client.v1.session.RESendSession;
import cn.ac.iie.di.global.GlobalParas;
import cn.ac.iie.di.msg.JsonMsgSender.SessionPool;
import cn.ac.iie.di.tools.GenerateMD5;
//import cn.ac.iie.di.tools.LongHashCode;
//import cn.ac.iie.di.tools.MMUrlPath;
import cn.ac.iie.di.tools.SplitJsonArray;
import cn.ac.iie.di.tools.TimeFormat;
//import cn.ac.iie.di.tools.TimeTransfer;
import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.logging.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author lenovo-pc
 */
public class JsonMsgTask implements Runnable {
    
    private final List<Map> jsonList;
    private String sendName;
    private String type_msg = null;
    private RESendSession session = null;
    
    private HashMap<String, String> JsonData = new HashMap<>();//存储Json中的数据1
    static private final Logger logger = Logger.getLogger(JsonMsgTask.class.getName());
    static private final AtomicInteger count = new AtomicInteger(0);

//    TrsCkmSoapClient client = new TrsCkmSoapClient();
    public static void printLog(int n) {
        if (count.addAndGet(n) > 500) {
            boolean print = false;
            int cur = 0;
            synchronized (count) {
                cur = count.get();
                if (cur > 500) {
                    count.addAndGet(-cur);
                    print = true;
                }
            }
            if (print) {
                logger.info("The imsg parser " + cur);
            }
        }
    }
    
    private final SessionPool pool;
    
    public JsonMsgTask(List<Map> jsonList, SessionPool pool, String sendName, String type_msg) {
        this.jsonList = jsonList;
        this.pool = pool;
        this.sendName = sendName;
        this.type_msg = type_msg;
    }
    
    @Override
    public void run() {
//        client.SetServer(GlobalParas.IP_TRS, "admin", "trsadmin");

        String str_pid = "";
        long line = 0;
        try {
            this.session = pool.borrowSession();
            for (Map sendMap : jsonList) {
                if (sendMap != null && !sendMap.isEmpty()) {
                    try {
                        logger.debug("tyep msg " + this.type_msg);
                        for (String name : this.type_msg.split("\\|")) {
                            setColName(name.split(":")[0], sendMap.get(name.split(":")[0]), name.split(":")[1]);
                        }
                        try {
                            this.session.add();
                            line++;
                        } catch (Exception e) {
                            sendMSG(this.session);
                            logger.info(this.sendName + " successful send " + line);
                            line = 0;
                            this.session.add();
                            line++;
                        }
                        
                    } catch (Exception ex) {
                        logger.error("The session add is wrong:" + ex, ex);
                    }
                }
            }
            sendMSG(this.session);
            logger.info(this.sendName + " successful send " + line);
            line = 0;
        } catch (Exception ex) {
            logger.error("know " + this.sendName + " Task error " + ex, ex);
        } finally {
            if (this.session != null) {
                pool.returnSession(this.session);
            }
        }
    }
    
    public void sendMSG(RESendSession session) {
        while (true) {
            try {
                session.flush();
                break;
            } catch (Exception ex) {
                logger.info("what's up buddy ? how's it going ?" + ex, ex);
            }
        }
    }
    
    public void setColName(String colName, Object colValue, String type) throws RESessionException {
        switch (type) {
            case "int":
                if (colValue != null && !colValue.toString().trim().isEmpty() && !"null".equals(colValue.toString().trim())) {
                    session.setInt(colName, Integer.parseInt(colValue.toString()));
                } else {
                    session.setInt(colName, -1);
                }
                break;
            case "ints":
                if (colValue != null) {
                    List<Integer> ints = (List) colValue;
                    logger.debug(ints.size() + " +++++++" + colName + "++++++++ " + ints.toString());
//                    Integer[] integers = ints.toArray(new Integer[ints.size()]);
                    int[] intArray = new int[ints.size()];
                    for (int i = 0; i < ints.size(); i++) {
                        if (ints.get(i) != null) {
                            intArray[i] = ints.get(i);
                        } else {
                            intArray[i] = -1;
                        }
                        
                    }
                    session.setInts(colName, intArray);
                } else {
                    session.setInts(colName, new int[0]);
                }
                break;
            case "longs":
                if (colValue != null) {
                    List<Long> ints = (List) colValue;
                    logger.debug(ints.size() + " +++++++" + colName + "++++++++ " + ints.toString());
                    long[] intArray = new long[ints.size()];
                    for (int i = 0; i < ints.size(); i++) {
                        intArray[i] = ints.get(i);
                    }
                    session.setLongs(colName, intArray);
                } else {
                    session.setLongs(colName, new long[0]);
                }
                break;
            case "long":
                if (colValue != null && !colValue.toString().trim().isEmpty() && !"null".equals(colValue.toString().trim())) {
                    session.setLong(colName, Long.parseLong(colValue.toString()));
                } else {
                    session.setLong(colName, -1);
                }
                break;
            case "string":
                if (colValue != null && !colValue.toString().trim().isEmpty() && !"null".equals(colValue.toString().trim())) {
                    if ("q_ip_sendcity".equals(colName)) {
                        logger.info("xxxxxxxxxxxxx " + colValue.toString());
                    }
                    session.setString(colName, colValue.toString());
                } else {
                    session.setString(colName, "");
                }
                break;
            case "strings":
                if (colValue != null) {
                    List<String> ints = (List) colValue;
                    String[] strings = ints.toArray(new String[ints.size()]);
                    logger.info("streings id: " + Arrays.toString(strings));
                    session.setStrings(colName, strings);
                } else {
                    session.setStrings(colName, new String[0]);
                }
                break;
        }
    }
}
